(function() {
    console.log("Loading pages...");
    var isSearching = false;
    var sitesNum = 0;
    var currentTabId = null;
    var loadedFiles = new Set();
    var execScript = function(tabId, script) {
        chrome.scripting.executeScript({
            target: { tabId: tabId },
            func: script,
        });
    };
    var search = function() {
        var keyWord = document.getElementById("searchBox").value;
        console.log(keyWord);
        if(keyWord === null || keyWord === "") return;
        var load = ({
                        tabId: tabId,
                        plugins: plugins,
                        pluginInterfaces: pluginInterfaces
                    }) => {
            currentTabId = tabId;
            console.log(plugins, pluginInterfaces);
            var retistryPlugins = function(ps) {
                for(var {js: js} of ps) {
                    for(var jsFile of js) {
                        registry(jsFile);
                    }
                }
            };
            retistryPlugins(pluginInterfaces);
            retistryPlugins(plugins);

            // sitesNum = plugins.length;
            // isSearching = true;
            // Promise.all([
            // ]).then()
            return plugins;
        };
        var execPlugin = plugins => {
          plugins.forEach(plugin => {
              console.log(window[plugin.class_name]);
          });

        };
        getPlugins().then(load).then(execPlugin).catch(error => console.log(error));
    }

    var registry = function(url) {
        loadFile(url);
        return;
        console.log(url);
        chrome.scripting.executeScript({
            target: {tabId: currentTabId},
            files: [url]
        }, res => console.log(res));
    }

    var loadFile = function(file) {
        try {
            if(loadedFiles.has(file)) return;
            // TODO: we need a callback to continue when the script is executed
            var s = document.createElement('script');
            s.setAttribute('src', file);
            (document.head || document.body || document.documentElement || document).appendChild(s);
            loadedFiles.add(file);
        } catch(e) {
            console.log("Error: Registry.load " + file + " failed! " + e.message);
        }
    };


    var getPlugins = (cb) => new Promise((resolve, reject) => {
        console.log("getPlugins");
        console.log(chrome.runtime);
        chrome.runtime.sendMessage({action: "getSearchPlugins"}, (response) => {
            if (response) {
                resolve(response);
            } else {
                reject("response is invalid");
            }
        })
        console.log("getPlugins end");
    });
})();

const SEARCH_BOX = "searchBox";
const SEARCH_BUTTON = "searchButton";

function search() {
    var keyWord = document.getElementById(SEARCH_BOX).value;
    if(keyWord === null || keyWord === "") return;
    console.log(keyWord);
    console.log("searching...");
    chrome.runtime.sendMessage({action: "searchVideos"}, (response) => {
        // todo: implement search logic
    });
}

function main() {
    const url = new URL(window.location.href);
    document.getElementById(SEARCH_BOX).value = url.searchParams.get('q');
    document.getElementById(SEARCH_BUTTON).addEventListener("click", search);
    search();
}

export default main();